import { action, computed, observable } from 'mobx'

class AppleStore {
  @observable appleList = [
    {
      id: 1,
      weight: 100,
      isEaten: false
    },
    {
      id: 2,
      weight: 200,
      isEaten: false
    }
  ]
  @observable isAddingButton = false

  @action.bound eatApple(id) {
    const apple = this.appleList.find(apple=>apple.id === id)
    if(apple){
      apple.isEaten = true
    }
  }

  @action.bound addApple() {
    this.isAddingButton = true
    setTimeout(() => {
      const apple = {}
      apple.id = this.appleList.length + 1
      apple.isEaten = false
      const weight = Math.floor(Math.random()*10+200)
      apple.weight = weight
      this.appleList.push(apple)
      this.isAddingButton = false
    },2000)
  }

  @computed get status() {
    const status = {
      appleAll: {
        num: 0,
        totalWeight: 0
      },
      appleEaten: {
        num: 0,
        totalWeight: 0
      }
    }

    let weightAll = 0
    let weightEaten = 0
    let numAll = 0
    let numEaten = 0
    this.appleList.forEach(apple=>{
      weightAll = weightAll + apple.weight
      numAll++
      if (apple.isEaten) {
        numEaten++
        weightEaten = weightEaten + apple.weight
      }
    })

    console.log(numAll)
    status.appleAll.num = numAll
    status.appleAll.totalWeight = weightAll
    status.appleEaten.num = numEaten
    status.appleEaten.totalWeight = weightEaten

    return status
  }
}

const appleStore = new AppleStore()

export default appleStore;